package com.siwei.mes.service.erp.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.dto.PhbhistoryPhbDto;
import com.siwei.mes.entity.dto.PhbhistoryPhbInfo;
import com.siwei.mes.entity.erp.*;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.materials.Materials;
import com.siwei.mes.entity.mixproportion.MixProportion;
import com.siwei.mes.entity.mixproportion.MixProportionReport;
import com.siwei.mes.entity.mixproportion.MixProportionVerifyRecord;
import com.siwei.mes.entity.sync.erp.ErpProject;
import com.siwei.mes.entity.tgl.Tjlbycl;
import com.siwei.mes.entity.vo.ExperimentPrintVo;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.enums.SelfSupplyEnum;
import com.siwei.mes.mapper.erp.ItemorderMapper;
import com.siwei.mes.mapper.erp.PhbhistoryMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.materials.MaterialsMapper;
import com.siwei.mes.mapper.mixProportion.MixProportionVerifyRecordMapper;
import com.siwei.mes.mapper.syncErp.ErpProjectMapper;
import com.siwei.mes.mapper.tgl.TjlbyclMapper;
import com.siwei.mes.service.erp.PhbhistoryService;
import com.siwei.mes.service.erp.RwdextraService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ERP配合比修改记录(Phbhistory)表服务实现类
 *
 * @author linzi
 * @since 2024-09-05 21:37:19
 */
@Service
public class PhbhistoryServiceImpl implements PhbhistoryService {
    @Resource
    private PhbhistoryMapper phbhistoryMapper;
    @Resource
    private ItemorderMapper itemorderMapper;
    @Resource
    private TjlbyclMapper tjlbyclMapper;
    @Resource
    private MaterialsMapper materialsMapper;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private MixProportionVerifyRecordMapper mixProportionVerifyRecordMapper;
    @Resource
    private ErpProjectMapper erpProjectMapper;
    @Resource
    private RwdextraService rwdextraService;

    private static final String[] ORDER = {"水", "水泥", "粉煤灰", "矿渣粉", "粗骨料", "细骨料", "外掺料1", "外掺料2"};
    private static final Map<String, Integer> ORDER_MAP;

    static {
        ORDER_MAP = new HashMap<>();
        for (int i = 0; i < ORDER.length; i++) {
            ORDER_MAP.put(ORDER[i], i);
        }
    }

    @Override
    public List<Phbhistory> selectByRwdh(Integer frwd) {
        List<Phbhistory> phbhistoryList = phbhistoryMapper.selectByRwdh(frwd, null);
        for (Phbhistory phbhistory : phbhistoryList) {
            phbhistory.setBeforePhbList(Phbhistory.jsonToObjList(phbhistory.getBeforephb()));
            phbhistory.setAfterPhbList(Phbhistory.jsonToObjList(phbhistory.getAfterphb()));
        }
        return phbhistoryList;
    }

    @Override
    public List<Phbhistory> selectByRwdhAndPhb(Integer frwd, MixProportion mixProportion) {
        MixProportionReport mixProportionReport = JsonUtils.getObject(mixProportion.getProportionMaterial(), MixProportionReport.class);
        List<Phbhistory> phbhistoryList = phbhistoryMapper.selectByRwdh(frwd, 0);
        List<Phbhistory> validPhbhistoryList = new ArrayList<>(); // 用于存储有效的phbhistory对象
        this.setValidPhbhistoryList(validPhbhistoryList,phbhistoryList,frwd,mixProportionReport,null);
        return validPhbhistoryList;
    }

    @Override
    public Phbhistory selectByRwdhAndPhbOne(Integer frwd, MixProportion mixProportion,Integer ITID,String mixtable) {
        MixProportionReport mixProportionReport = JsonUtils.getObject(mixProportion.getProportionMaterial(), MixProportionReport.class);
        Phbhistory phbhistoryList = phbhistoryMapper.selectByRwdhByITID(frwd, 0,ITID,mixtable);
        this.setValidPhbhistoryListTwo(phbhistoryList,frwd,mixProportionReport,ITID);
        return phbhistoryList;
    }

    @Override
    public void sortPhbhistoryList(List<Phbhistory> phbhistoryList,MixProportion mixProportion) {
        /**去重**/
        Set<String> afterPhbSet = new HashSet<>();
        for (Phbhistory phbhistory : phbhistoryList) {
            phbhistory.setBeforePhbList(Phbhistory.jsonToObjList(phbhistory.getBeforephb()));
            phbhistory.setAfterPhbList(Phbhistory.jsonToObjList(phbhistory.getAfterphb()));
            for (PhbhistoryPhbInfo phbInfo : phbhistory.getAfterPhbList()) {
                String name = phbInfo.getName();
                String pzgg = phbInfo.getPzgg();
                /**将两个键的值组合成一个字符串作为去重的依据**/
                String combinedKey = name + "_" + pzgg;
                if (!afterPhbSet.contains(combinedKey)) {
                    afterPhbSet.add(combinedKey);
                }
            }
        }
        MixProportionReport mixProportionReport = JsonUtils.getObject(mixProportion.getProportionMaterial(), MixProportionReport.class);
        /*重新遍历 给修改后配合比信息(打印相关数据)数组赋值*/
        for (Phbhistory phbhistory : phbhistoryList) {
            /*根据指定数组值排序*/
            List<PhbhistoryPhbDto> phbhistoryPhbDtoList = phbhistory.getAfterPhbDtoList();
            PhbhistoryPhbDto phbhistoryPhbDto = new PhbhistoryPhbDto();
            for (String afterPhbKey : afterPhbSet) {
                String[] keys = afterPhbKey.split("_");
                String name = keys[0];
                String pzgg = keys[1];
                boolean isFlag =  true;
                for (PhbhistoryPhbDto phbInfo : phbhistoryPhbDtoList) {
                    String nameOld = phbInfo.getWlmc();
                    String pzggOld = phbInfo.getWlgg();
                    if(name.equals(nameOld)  && pzgg.equals(pzggOld)){
                        isFlag = false;
                    }
                }
                if(isFlag){
                    PhbhistoryPhbInfo phbInfo = new PhbhistoryPhbInfo().setName(name).setPzgg(pzgg);
                    boolean isPhbSetValue = checkPhbSetValue(phbhistoryPhbDto, mixProportionReport, phbInfo);
                    if (!isPhbSetValue) {
                        /**配合比中找不到 再找物料表是否存在**/
                        isPhbSetValue = setValueDto(name, pzgg, phbhistoryPhbDto);
                    }
                    if (!isPhbSetValue) {
                        phbhistoryPhbDto.setCllx(name);
                        phbhistoryPhbDto.setClmc(name);
                        phbhistoryPhbDto.setClgg(pzgg);
                        phbhistoryPhbDto.setWlmc(name);
                        phbhistoryPhbDto.setWlgg(pzgg);
                    }
                    phbhistoryPhbDtoList.add(phbhistoryPhbDto);
                }
            }
            phbhistory.setAfterPhbDtoList(
                    phbhistoryPhbDtoList.stream()
                            .sorted(Comparator
                                    // 1. cllx 顺序
                                    .comparing((PhbhistoryPhbDto p) -> ORDER_MAP.getOrDefault(p.getCllx(), Integer.MAX_VALUE))
                                    // 2. 同一 cllx 下按 mpfyl 数值降序，空值最后
                                    .thenComparing(
                                            (PhbhistoryPhbDto p) -> toBigDecimal(p.getMpfyl()),
                                            Comparator.nullsLast(Comparator.reverseOrder())))
                            .collect(Collectors.toList())
            );
        }
        phbhistoryList.sort(Comparator.comparing(Phbhistory::getCreatetime));
    }

    private void setValidPhbhistoryList(List<Phbhistory> validPhbhistoryList,List<Phbhistory> phbhistoryList,Integer frwd,MixProportionReport mixProportionReport,Integer ITID){
        /**去重**/
        Set<String> afterPhbSet = new HashSet<>();
        for (Phbhistory phbhistory : phbhistoryList) {
            phbhistory.setBeforePhbList(Phbhistory.jsonToObjList(phbhistory.getBeforephb()));
            phbhistory.setAfterPhbList(Phbhistory.jsonToObjList(phbhistory.getAfterphb()));
            for (PhbhistoryPhbInfo phbInfo : phbhistory.getAfterPhbList()) {
                String name = phbInfo.getName();
                String pzgg = phbInfo.getPzgg();
                /**将两个键的值组合成一个字符串作为去重的依据**/
                String combinedKey = name + "_" + pzgg;
                if (!afterPhbSet.contains(combinedKey)) {
                    afterPhbSet.add(combinedKey);
                }
            }
        }
        /*重新遍历 给修改后配合比信息(打印相关数据)数组赋值*/
        for (Phbhistory phbhistory : phbhistoryList) {
            List<PhbhistoryPhbDto> phbhistoryPhbDtoList = new ArrayList();
            /**获取任务单第一车小票**/
            Itemorder itemorder;
            if(ITID !=null){
                itemorder = itemorderMapper.loadByItId(ITID);
            }else{
                itemorder = itemorderMapper.selectByFrwdhNotSc(frwd, phbhistory.getCreatetime());
            }
            if (itemorder != null) {
                for (String afterPhbKey : afterPhbSet) {
                    String[] keys = afterPhbKey.split("_");
                    String name = keys[0];
                    String pzgg = keys[1];
                    PhbhistoryPhbDto phbhistoryPhbDto = new PhbhistoryPhbDto();
                    boolean isMatch = true;
                    /**去除字符串中的[]**/
                    String jlbidsStr = itemorder.getJlbids().replace("[", "").replace("]", "");
                    Integer jlbIds = null;
                    if(jlbidsStr.contains(",")){
                        String[] jlbidsList = jlbidsStr.split(",");
                        if(jlbidsList.length>0){
                            jlbIds = Integer.valueOf(jlbidsStr.split(",")[0]);
                        }else{
                            jlbIds = -1;
                        }
                    }else{
                        jlbIds = Integer.valueOf(jlbidsStr);
                    }
                    List<Tjlbycl> tjlbyclList = tjlbyclMapper.getList(new Tjlbycl().setFNo(jlbIds).setFPanNo(1));
                    for (PhbhistoryPhbInfo phbInfo : phbhistory.getAfterPhbList()) {
                        if (name.equals(phbInfo.getName()) && pzgg.equals(phbInfo.getPzgg())) {
                            for (Tjlbycl tjlbycl : tjlbyclList) {
                                /**遍历tgl盘次信息 获取第一次开票中的含水量**/
                                if (tjlbycl.getFYlmc().equals(phbInfo.getName()) && tjlbycl.getFPzgg().equals(phbInfo.getPzgg())) {
                                    phbhistoryPhbDto.setHsl(tjlbycl.getFHsl() == 0 ? null : String.valueOf(tjlbycl.getFHsl()));
                                    break;
                                }
                            }
                            /**配合比中匹配信息**/
                            boolean isPhbSetValue = checkPhbSetValue(phbhistoryPhbDto, mixProportionReport, phbInfo);
                            if (!isPhbSetValue) {
                                /**配合比中找不到 再找物料表是否存在**/
                                isPhbSetValue = setValueDto(name, pzgg, phbhistoryPhbDto);
                            }
                            phbhistoryPhbDto.setTzhmpfyl(phbInfo.getYl());
                            /**如果都没有，取历史记录中的 name和pzgg**/
                            if (!isPhbSetValue) {
                                phbhistoryPhbDto.setCllx(name);
                                phbhistoryPhbDto.setClmc(name);
                                phbhistoryPhbDto.setClgg(pzgg);
                                phbhistoryPhbDto.setWlmc(name);
                                phbhistoryPhbDto.setWlgg(pzgg);
                            }
                            isMatch = false;
                        }
                    }
                    /**如果调整记录不存在数据，也需要取配合比获取材料信息填充，配合比中没有，才用调整记录的name和pzgg**/
                    if (isMatch) {
                        PhbhistoryPhbInfo phbInfo = new PhbhistoryPhbInfo().setName(name).setPzgg(pzgg);
                        boolean isPhbSetValue = checkPhbSetValue(phbhistoryPhbDto, mixProportionReport, phbInfo);
                        if (!isPhbSetValue) {
                            /**配合比中找不到 再找物料表是否存在**/
                            isPhbSetValue = setValueDto(name, pzgg, phbhistoryPhbDto);
                        }
                        if (!isPhbSetValue) {
                            phbhistoryPhbDto.setCllx(name);
                            phbhistoryPhbDto.setClmc(name);
                            phbhistoryPhbDto.setClgg(pzgg);
                            phbhistoryPhbDto.setWlmc(name);
                            phbhistoryPhbDto.setWlgg(pzgg);
                        }
                    }
                    phbhistoryPhbDtoList.add(phbhistoryPhbDto);
                }
                /*根据指定数组值排序*/

                phbhistory.setAfterPhbDtoList(
                        phbhistoryPhbDtoList.stream()
                                .sorted(Comparator
                                        // 1. cllx 顺序
                                        .comparing((PhbhistoryPhbDto p) -> ORDER_MAP.getOrDefault(p.getCllx(), Integer.MAX_VALUE))
                                        // 2. 同一 cllx 下按 mpfyl 数值降序，空值最后
                                        .thenComparing(
                                                (PhbhistoryPhbDto p) -> toBigDecimal(p.getMpfyl()),
                                                Comparator.nullsLast(Comparator.reverseOrder())))
                                .collect(Collectors.toList())
                );
                if (itemorder != null) {
                    validPhbhistoryList.add(phbhistory);
                }
            }
        }
    }

    private void setValidPhbhistoryListTwo(Phbhistory phbhistoryList,Integer frwd,MixProportionReport mixProportionReport,Integer ITID){
        /**去重**/
        Set<String> afterPhbSet = new HashSet<>();
        phbhistoryList.setBeforePhbList(Phbhistory.jsonToObjList(phbhistoryList.getBeforephb()));
        phbhistoryList.setAfterPhbList(Phbhistory.jsonToObjList(phbhistoryList.getAfterphb()));
        for (PhbhistoryPhbInfo phbInfo : phbhistoryList.getAfterPhbList()) {
            String name = phbInfo.getName();
            String pzgg = phbInfo.getPzgg();
            /**将两个键的值组合成一个字符串作为去重的依据**/
            String combinedKey = name + "_" + pzgg;
            if (!afterPhbSet.contains(combinedKey)) {
                afterPhbSet.add(combinedKey);
            }
        }

        List<PhbhistoryPhbDto> phbhistoryPhbDtoList = new ArrayList();
        /**获取任务单第一车小票**/
        Itemorder itemorder;
        if(ITID !=null){
            itemorder = itemorderMapper.loadByItId(ITID);
        }else{
            itemorder = itemorderMapper.selectByFrwdhNotSc(frwd, phbhistoryList.getCreatetime());
        }
        if (itemorder != null) {
            for (String afterPhbKey : afterPhbSet) {
                String[] keys = afterPhbKey.split("_");
                String name = keys[0];
                String pzgg = keys[1];
                PhbhistoryPhbDto phbhistoryPhbDto = new PhbhistoryPhbDto();
                boolean isMatch = true;
                /**去除字符串中的[]**/
                String jlbidsStr = itemorder.getJlbids().replace("[", "").replace("]", "");
                Integer jlbIds = null;
                if(jlbidsStr.contains(",")){
                    String[] jlbidsList = jlbidsStr.split(",");
                    if(jlbidsList.length>0){
                        jlbIds = Integer.valueOf(jlbidsStr.split(",")[0]);
                    }else{
                        jlbIds = -1;
                    }
                }else{
                    jlbIds = Integer.valueOf(jlbidsStr);
                }
                List<Tjlbycl> tjlbyclList = tjlbyclMapper.getList(new Tjlbycl().setFNo(jlbIds).setFPanNo(1));
                for (PhbhistoryPhbInfo phbInfo : phbhistoryList.getAfterPhbList()) {
                    if (name.equals(phbInfo.getName()) && pzgg.equals(phbInfo.getPzgg())) {
                        for (Tjlbycl tjlbycl : tjlbyclList) {
                            /**遍历tgl盘次信息 获取第一次开票中的含水量**/
                            if (tjlbycl.getFYlmc().equals(phbInfo.getName()) && tjlbycl.getFPzgg().equals(phbInfo.getPzgg())) {
                                phbhistoryPhbDto.setHsl(tjlbycl.getFHsl() == 0 ? null : String.valueOf(tjlbycl.getFHsl()));
                                break;
                            }
                        }
                        /**配合比中匹配信息**/
                        boolean isPhbSetValue = checkPhbSetValue(phbhistoryPhbDto, mixProportionReport, phbInfo);
                        if (!isPhbSetValue) {
                            /**配合比中找不到 再找物料表是否存在**/
                            isPhbSetValue = setValueDto(name, pzgg, phbhistoryPhbDto);
                        }
                        phbhistoryPhbDto.setTzhmpfyl(phbInfo.getYl());
                        /**如果都没有，取历史记录中的 name和pzgg**/
                        if (!isPhbSetValue) {
                            phbhistoryPhbDto.setCllx(name);
                            phbhistoryPhbDto.setClmc(name);
                            phbhistoryPhbDto.setClgg(pzgg);
                            phbhistoryPhbDto.setWlmc(name);
                            phbhistoryPhbDto.setWlgg(pzgg);
                        }
                        isMatch = false;
                    }
                }
                /**如果调整记录不存在数据，也需要取配合比获取材料信息填充，配合比中没有，才用调整记录的name和pzgg**/
                if (isMatch) {
                    PhbhistoryPhbInfo phbInfo = new PhbhistoryPhbInfo().setName(name).setPzgg(pzgg);
                    boolean isPhbSetValue = checkPhbSetValue(phbhistoryPhbDto, mixProportionReport, phbInfo);
                    if (!isPhbSetValue) {
                        /**配合比中找不到 再找物料表是否存在**/
                        isPhbSetValue = setValueDto(name, pzgg, phbhistoryPhbDto);
                    }
                    if (!isPhbSetValue) {
                        phbhistoryPhbDto.setCllx(name);
                        phbhistoryPhbDto.setClmc(name);
                        phbhistoryPhbDto.setClgg(pzgg);
                        phbhistoryPhbDto.setWlmc(name);
                        phbhistoryPhbDto.setWlgg(pzgg);
                    }
                }
                phbhistoryPhbDtoList.add(phbhistoryPhbDto);
            }
            /*根据指定数组值排序*/
            phbhistoryList.setAfterPhbDtoList(
                    phbhistoryPhbDtoList.stream()
                            .sorted(Comparator
                                    // 1. cllx 顺序
                                    .comparing((PhbhistoryPhbDto p) -> ORDER_MAP.getOrDefault(p.getCllx(), Integer.MAX_VALUE))
                                    // 2. 同一 cllx 下按 mpfyl 数值降序，空值最后
                                    .thenComparing(
                                            (PhbhistoryPhbDto p) -> toBigDecimal(p.getMpfyl()),
                                            Comparator.nullsLast(Comparator.reverseOrder())))
                            .collect(Collectors.toList())
            );
        }
    }

    /* 工具方法：把字符串安全地转 BigDecimal，空/非法返回 null */
    private static BigDecimal toBigDecimal(String str) {
        if (str == null || str.trim().isEmpty()) {
            return null;
        }
        try {
            return new BigDecimal(str.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public Phbhistory selectByRwdhAndTime(Integer frwd, MixProportion mixProportion,Integer isDesc) {
        Phbhistory phbhistory = phbhistoryMapper.selectByRwdhAndTime(frwd,isDesc);
        if(mixProportion == null){
            return phbhistory;
        }
        MixProportionReport mixProportionReport = JsonUtils.getObject(mixProportion.getProportionMaterial(), MixProportionReport.class);
        if(phbhistory != null){
            /**获取任务单第一车小票**/
            Itemorder itemorder = itemorderMapper.selectByFrwdhNotSc(frwd, phbhistory.getCreatetime());
            if (itemorder != null) {
                /**去除字符串中的[]**/
                List<Integer> jlbidsList = parseJlbIds(itemorder.getJlbids());
                List<Tjlbycl> tjlbyclList = new ArrayList();
                if(CollectionUtil.isNotEmpty(jlbidsList)){
                    tjlbyclList = tjlbyclMapper.getList(new Tjlbycl().setFNo(jlbidsList.get(0)).setFPanNo(1));
                }
                if (phbhistory != null) {
                    phbhistory.setBeforePhbList(Phbhistory.jsonToObjList(phbhistory.getBeforephb()));
                    phbhistory.setAfterPhbList(Phbhistory.jsonToObjList(phbhistory.getAfterphb()));
                    List<PhbhistoryPhbInfo> phbList;
                    /** 修改后配合比信息,如果没有 取修改前配合比信息 如果不存在 则退出匹配逻辑*/
                    if(CollectionUtil.isNotEmpty(phbhistory.getAfterPhbList())){
                        phbList = phbhistory.getAfterPhbList();
                    }else if(CollectionUtil.isNotEmpty(phbhistory.getBeforePhbList())) {
                        phbList = phbhistory.getBeforePhbList();
                    }else {
                        return phbhistory;
                    }
                    List<PhbhistoryPhbDto> phbhistoryPhbDtoList = new ArrayList();
                    for (PhbhistoryPhbInfo phbInfo :phbList) {
                        PhbhistoryPhbDto phbhistoryPhbDto = new PhbhistoryPhbDto();
                        for (Tjlbycl tjlbycl : tjlbyclList) {
                            /**遍历tgl盘次信息 获取第一次开票中的含水量**/
                            if (tjlbycl.getFYlmc().equals(phbInfo.getName()) && tjlbycl.getFPzgg().equals(phbInfo.getPzgg())) {
                                phbhistoryPhbDto.setHsl(tjlbycl.getFHsl() == 0 ? null : String.valueOf(tjlbycl.getFHsl()));
                            }
                        }
                        phbhistoryPhbDto.setTzhmpfyl(phbInfo.getYl());
                        if (!checkPhbSetValue(phbhistoryPhbDto, mixProportionReport, phbInfo)) {
                            /**配合比中找不到 再找物料表是否存在**/
                            if (!setValueDto(phbInfo.getName(), phbInfo.getPzgg(), phbhistoryPhbDto)) {
                                phbhistoryPhbDto.setCllx(phbInfo.getName());
                                phbhistoryPhbDto.setClmc(phbInfo.getName());
                                phbhistoryPhbDto.setClgg(phbInfo.getPzgg());
                                phbhistoryPhbDto.setWlmc(phbInfo.getName());
                                phbhistoryPhbDto.setWlgg(phbInfo.getPzgg());
                            }
                        }else {
                            /** 判断如果报告编号不存在 再匹配一次*/
                            if("1".equals(phbhistoryPhbDto.getIsNotGg())){
                                Rwdextra rwdextra = rwdextraService.selectByFrwdh(frwd);
                                /**这里根据工程名称+配合比唯一标识 查询配合比验证记录 一个配合比同一个工程只能有一条记录*/
                                MixProportionVerifyRecord verifyRecord = mixProportionVerifyRecordMapper.selectByMixIdAndProjectName(mixProportion.getId(), rwdextra.getRwdextraInfo().getFGcmc());
                                RwdextraExtend entity = rwdextra.getRwdextraExtend();
                                ErpProject project = erpProjectMapper.loadById(entity.getErpProjectId());
                                ProjectMaterialsReport projectMaterialsReport = new ProjectMaterialsReport();
                                if (project != null && project.getProjectMaterial() != null) {
                                    projectMaterialsReport = JsonUtils.getObject(project.getProjectMaterial(), ProjectMaterialsReport.class);
                                }
                                checkPhbSetTz(phbhistoryPhbDto,mixProportionReport,phbInfo,verifyRecord,projectMaterialsReport);
                                Date planTime = rwdextra.getPlantime();
                                getPrintTaskExperimentInfo(phbhistoryPhbDto,planTime);
                            }
                        }
                        phbhistoryPhbDtoList.add(phbhistoryPhbDto);
                    }
                    /*根据指定数组值排序*/
                    phbhistory.setAfterPhbDtoList(phbhistoryPhbDtoList.stream()
                            .sorted(Comparator.comparing(p -> ORDER_MAP.getOrDefault(p.getCllx(), Integer.MAX_VALUE)))
                            .collect(Collectors.toList()));
                    mixProportion.setProportionMaterial(JsonUtils.beanToObject(mixProportionReport));
                    return phbhistory;
                } else {
                    return null;
                }
            }
        }
        return null;
    }

    /**
     * 任务单的配比，匹配ERP配合比历史记录 组装对应的 ERP配合比历史记录(打印相关数据)数组
     *
     * @param phbhistoryPhbDto     ERP配合比历史记录(打印相关数据)
     * @param mixProportionReport  配合比报表信息
     * @param phbInfo              ERP配合比历史记录
     * @return
     */
    private boolean checkPhbSetValue(PhbhistoryPhbDto phbhistoryPhbDto,  MixProportionReport mixProportionReport, PhbhistoryPhbInfo phbInfo) {
        MixProportionReport.BgxxInfo sn = mixProportionReport.getSn();//水泥
        if (isCheckValue(sn, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo fmh = mixProportionReport.getFmh();//粉煤灰
        if (isCheckValue(fmh, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo kzf = mixProportionReport.getKzf();//矿渣粉
        if (isCheckValue(kzf, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo cgl = mixProportionReport.getCgl();//粗骨料
        if (isCheckValue(cgl, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo xgl = mixProportionReport.getXgl();//细骨料
        if (isCheckValue(xgl, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo wjj1 = mixProportionReport.getWjj1();//外加剂1
        if (isCheckValue(wjj1, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo wjj2 = mixProportionReport.getWjj2();//外加剂2
        if (isCheckValue(wjj2, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo wcl1 = mixProportionReport.getWcl1();//外掺料1
        if (isCheckValue(wcl1, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo wcl2 = mixProportionReport.getWcl2();//外掺料2
        if (isCheckValue(wcl2, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        MixProportionReport.BgxxInfo water = mixProportionReport.getWater();//水
        if (isCheckValue(water, phbInfo, phbhistoryPhbDto)) {
            return true;
        }
        return false;
    }

    private void checkPhbSetTz(PhbhistoryPhbDto phbhistoryPhbDto,  MixProportionReport mixProportionReport, PhbhistoryPhbInfo phbInfo,MixProportionVerifyRecord verifyRecord,ProjectMaterialsReport projectMaterialsReport) {
        MixProportionReport.BgxxInfo sn = mixProportionReport.getSn();//水泥
        if (isCheck(sn, phbInfo)) {
            if(verifyRecord != null){
                phbhistoryPhbDto.setFactory(verifyRecord.getSnFactory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getSn());
            return ;
        }
        MixProportionReport.BgxxInfo fmh = mixProportionReport.getFmh();//粉煤灰
        if (isCheck(fmh, phbInfo)) {
            if(verifyRecord != null) {
                phbhistoryPhbDto.setFactory(verifyRecord.getFmh1Factory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getFmh());
            return ;
        }
        MixProportionReport.BgxxInfo kzf = mixProportionReport.getKzf();//矿渣粉
        if (isCheck(kzf, phbInfo)) {
            if(verifyRecord != null) {
                phbhistoryPhbDto.setFactory(verifyRecord.getKzf1Factory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getKzf());
            return ;
        }
        MixProportionReport.BgxxInfo cgl = mixProportionReport.getCgl();//粗骨料
        if (isCheck(cgl, phbInfo)) {
            if(verifyRecord != null) {
                phbhistoryPhbDto.setFactory(verifyRecord.getCglFactory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getCgl());
            return ;
        }
        MixProportionReport.BgxxInfo xgl = mixProportionReport.getXgl();//细骨料
        if (isCheck(xgl, phbInfo)) {
            if(verifyRecord != null) {
                phbhistoryPhbDto.setFactory(verifyRecord.getXglFactory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getXgl());
            return ;
        }
        MixProportionReport.BgxxInfo wjj1 = mixProportionReport.getWjj1();//外加剂1
        if (isCheck(wjj1, phbInfo)) {
            if(verifyRecord != null){
                phbhistoryPhbDto.setFactory(verifyRecord.getWjj1Factory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getWjj1());
            return ;
        }
        MixProportionReport.BgxxInfo wjj2 = mixProportionReport.getWjj2();//外加剂2
        if (isCheck(wjj2, phbInfo)) {
            if(verifyRecord != null){
                phbhistoryPhbDto.setFactory(verifyRecord.getWjj2Factory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getWjj1());
            return ;
        }
        MixProportionReport.BgxxInfo wcl1 = mixProportionReport.getWcl1();//外掺料1
        if (isCheck(wcl1, phbInfo)) {
            if(verifyRecord != null){
                phbhistoryPhbDto.setFactory(verifyRecord.getWcl1Factory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getWcl1());
            return ;
        }
        MixProportionReport.BgxxInfo wcl2 = mixProportionReport.getWcl2();//外掺料2
        if (isCheck(wcl2, phbInfo)) {
            if(verifyRecord != null){
                phbhistoryPhbDto.setFactory(verifyRecord.getWcl2Factory());
            }
            phbhistoryPhbDto.setMaterialsInfo(projectMaterialsReport.getWcl2());
            return ;
        }
        return ;
    }

    /**
     * 任务单的配比，去拿到对应材料类型，材料名称 或者物料名称和物料规格，匹配修改记录中的 原材料名称  品种规格 组装到 打印对象中
     *
     * @param bgxxInfo         配合比原材料信息
     * @param phbInfo          ERP配合比历史记录
     * @param phbhistoryPhbDto ERP配合比历史记录(打印相关数据)
     * @return
     */
    private boolean isCheckValue(MixProportionReport.BgxxInfo bgxxInfo, PhbhistoryPhbInfo phbInfo, PhbhistoryPhbDto phbhistoryPhbDto) {
        if ((bgxxInfo.getWlmc().equals(phbInfo.getName()) && bgxxInfo.getWlgg().equals(phbInfo.getPzgg()))
                || (bgxxInfo.getClmc().equals(phbInfo.getName()) && bgxxInfo.getClgg().equals(phbInfo.getPzgg())) || (bgxxInfo.getWlmc().equals(phbInfo.getName()) && !"水".equals(phbInfo.getName()))) {
            if (StringUtils.isNotBlank(bgxxInfo.getCllx()) && bgxxInfo.getCllx().matches("\\d+")) {
                phbhistoryPhbDto.setCllx(MaterialsEnum.selectByCode(Integer.valueOf(bgxxInfo.getCllx())).getName());
            } else {
                phbhistoryPhbDto.setCllx(bgxxInfo.getClmc());
            }
            if (StringUtils.isBlank(bgxxInfo.getClmc())) {
                phbhistoryPhbDto.setClmc(bgxxInfo.getWlmc());
                phbhistoryPhbDto.setClgg(bgxxInfo.getWlgg());
            }else{
                phbhistoryPhbDto.setClmc(bgxxInfo.getClmc());
                phbhistoryPhbDto.setClgg(bgxxInfo.getClgg());
            }
            if (StringUtils.isBlank(bgxxInfo.getWlmc())) {
                phbhistoryPhbDto.setWlmc(phbInfo.getName());
                phbhistoryPhbDto.setWlgg(phbInfo.getPzgg());
            } else {
                phbhistoryPhbDto.setWlmc(bgxxInfo.getWlmc());
                phbhistoryPhbDto.setWlgg(bgxxInfo.getWlgg());
            }
            /** 如果协会报告编号不存在 再查询一次数据赋值*/
            if(StringUtils.isBlank(bgxxInfo.getXhbgbh()) && StringUtils.isNotBlank(bgxxInfo.getPktzid())){
                Experiment experiment = experimentMapper.loadById(Long.valueOf(bgxxInfo.getPktzid()));
                phbhistoryPhbDto.setXhbgbh(experiment.getReportNo());phbhistoryPhbDto.setCj(experiment.getFactory());
                phbhistoryPhbDto.setCj(experiment.getFactory());
                phbhistoryPhbDto.setCjjc(experiment.getFactoryCalled());
                phbhistoryPhbDto.setGys(experiment.getSupplyCompanyName());
                phbhistoryPhbDto.setGysjc(experiment.getSupplyCompanyCalled());
            }else{
                phbhistoryPhbDto.setCj(bgxxInfo.getCj());
                phbhistoryPhbDto.setCjjc(bgxxInfo.getCjjc());
                phbhistoryPhbDto.setGys(bgxxInfo.getGys());
                phbhistoryPhbDto.setGysjc(bgxxInfo.getGysjc());
                phbhistoryPhbDto.setXhbgbh(bgxxInfo.getXhbgbh());
            }
            bgxxInfo.setDyphbtzhmpfyl(phbInfo.getYl() == 0 ? null : String.valueOf(phbInfo.getYl()));
            if(bgxxInfo.getWlmc().equals(phbInfo.getName()) && !bgxxInfo.getWlgg().equals(phbInfo.getPzgg())){
                setValueDto(phbInfo.getName(), phbInfo.getPzgg(), phbhistoryPhbDto);
                phbhistoryPhbDto.setWlgg(phbInfo.getPzgg());
                phbhistoryPhbDto.setIsNotGg("1");
                phbhistoryPhbDto.setBgxxInfo(bgxxInfo);
            }else {
                phbhistoryPhbDto.setIsNotGg("0");
                phbhistoryPhbDto.setMpfyl(bgxxInfo.getScyl());
                bgxxInfo.setDyphbhsl(phbhistoryPhbDto.getHsl());
            }
            return true;
        } else {
            return false;
        }
    }

    private boolean isCheck(MixProportionReport.BgxxInfo bgxxInfo, PhbhistoryPhbInfo phbInfo) {
        if (bgxxInfo.getWlmc().equals(phbInfo.getName()) && !bgxxInfo.getWlgg().equals(phbInfo.getPzgg())) {
            return true;
        }else {
            return false;
        }
    }

    private boolean setValueDto(String name, String pzgg, PhbhistoryPhbDto phbhistoryPhbDto) {
        Materials materials = materialsMapper.loadByNameSpecs(new Materials().setMaterialName(name).setMaterialSpecs(pzgg));
        if (materials != null) {
            phbhistoryPhbDto.setCllx(materials.getMaterialTypeName());
            phbhistoryPhbDto.setClmc(materials.getMaterialsConfigName());
            phbhistoryPhbDto.setClgg(materials.getMaterialsConfigSpec());
            phbhistoryPhbDto.setWlmc(materials.getMaterialName());
            phbhistoryPhbDto.setWlgg(materials.getMaterialSpecs());
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据配合中 材料名称+材料规格+材料类型 获取任务单的计划时间之前最近的一条
     *
     * @param phbhistoryPhbDto 配合比调整记录
     * @param planTime 计划时间
     * @return
     */
    private void getPrintTaskExperimentInfo(PhbhistoryPhbDto phbhistoryPhbDto, Date planTime) {
        String wlmc = phbhistoryPhbDto.getWlmc();//物料名称
        String wlgg = phbhistoryPhbDto.getWlgg();//物料规格
        ExperimentPrintVo experimentPrintVo = new ExperimentPrintVo().setWlmc(wlmc).setWlgg(wlgg).setPlanTime(planTime);
        String factory = phbhistoryPhbDto.getFactory();
        ProjectMaterialsReport.MaterialsInfo materialsInfo = phbhistoryPhbDto.getMaterialsInfo();
        Experiment experiment;
        if (StringUtils.isNotBlank(factory)) {
            /**当配合比存在验证记录 任务单工程名称配合比验证记录相同  得到指定厂家的原材料报告**/
            experimentPrintVo.setFactory(factory);
            experiment = experimentMapper.getLastExperimentIdByFactory(experimentPrintVo);
        } else if (materialsInfo != null && StringUtils.isNotBlank(materialsInfo.getCllx()) && materialsInfo.getWlmc().equals(experimentPrintVo.getWlmc()) && materialsInfo.getWlgg().equals(experimentPrintVo.getWlgg())) {
            experimentPrintVo.setMaterialsValue(experimentPrintVo, materialsInfo);
            /**当对应工程有绑定物料, 并且物料名称 物料规格相同 根据物料  得到指定厂家的原材料报告**/
            experiment = experimentMapper.getLastExperimentIdByFactoryAndSupplyCompanyName(experimentPrintVo);
        } else {
            /**获取条件为非甲供  得到指定厂家的原材料报告**/
            experimentPrintVo.setSelfSupply(SelfSupplyEnum.YES.getCode());
            experiment = experimentMapper.getLastExperimentIdNotSelfSupply(experimentPrintVo);
        }
        if (experiment != null && StringUtils.isNotBlank(experiment.getReportNo())) {
            phbhistoryPhbDto.setFactory(experiment.getFactory());
            phbhistoryPhbDto.setCj(experiment.getFactory());
            phbhistoryPhbDto.setCjjc(experiment.getFactoryCalled());
            phbhistoryPhbDto.setGys(experiment.getSupplyCompanyName());
            phbhistoryPhbDto.setGysjc(experiment.getSupplyCompanyCalled());
            phbhistoryPhbDto.setXhbgbh(experiment.getReportNo());
        }
    }

    public static List<Integer> parseJlbIds(String jlbIds) {
        String jlbIdsStr = jlbIds.replaceAll("[\\[\\]]", "");
        List<Integer> ids = new ArrayList<>();
        for (String num : jlbIdsStr.split(",")) {
            try {
                if (!num.trim().isEmpty()) {
                    ids.add(Integer.parseInt(num.trim()));
                }
            } catch (NumberFormatException e) {
                // 处理无效数字（例如记录日志）
                System.err.println("无效数字: " + num);
            }
        }
        return ids;
    }
}
